/* eslint-disable no-undef */
const net = require("net");
const http = require("http");
const agent = new http.Agent({ keepAlive: true });
// npm install node-os-utils --save
var osu = require("node-os-utils");
var old_net_in = 500000;
var old_net_out = 500000;
var config = require("./config.json");
var server_host = config.load_server_host;
const client = net.createConnection(
  { port: 8124, host: server_host },
  async () => {
    // 'connect' listener.
    console.log("connected to server!");
    var address = await getPublicIp();
    setInterval(async () => {
      var timestamp = new Date().getTime();
      var throughput = await getThroughput();
      var memory_ratio = await getMemoryRatio();
      var cpu_ratio = await getCpuRatio();
      var message = {
        address: address,
        timestamp: timestamp,
        throughput: throughput,
        memory_ratio: memory_ratio,
        cpu_ratio: cpu_ratio,
      };
      client.write(JSON.stringify(message) + "\r\n");
    }, 5000);
  }
);
client.on("data", (data) => {
  console.log(data.toString());
});
client.on("end", () => {
  console.log("disconnected from server");
});
// 获取公网ip
let getPublicIp = function () {
  return new Promise(function (resolve, reject) {
    http
      .get("http://httpbin.org/ip", { agent }, (res) => {
        res.on("data", (data) => {
          resolve(JSON.parse(data.toString()).origin);
        });
      })
      .on("error", (e) => {
        console.error(`Got error: ${e.message}`);
        reject(e);
      });
  });
};
// 获取cpu使用率
let getCpuRatio = function () {
  return new Promise(function (resolve) {
    var cpu = osu.cpu;
    cpu.usage().then((info) => {
      resolve((info / 100).toFixed(6));
    });
  });
};
// 获取内存使用率
let getMemoryRatio = function () {
  return new Promise(function (resolve) {
    var mem = osu.mem
    mem.used().then((info) => {
      resolve((info.usedMemMb / info.totalMemMb).toFixed(6));
    });
  });
};
// 获取网络带宽
let getThroughput = function () {
  return new Promise(function (resolve) {
    var netstat = osu.netstat;
    netstat.stats().then((info) => {
      var new_net_in = Number(info[1].inputBytes);
      var new_net_out = Number(info[1].outputBytes);
      resolve(
        (
          (new_net_out + new_net_in - old_net_in - old_net_out) /
          2097152
        ).toFixed(6)
      );
      old_net_in = new_net_in;
      old_net_out = new_net_out;
    });
  });
};
